package com.example.activitidemo.controller;

import com.example.activitidemo.RespBase;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.task.runtime.TaskAdminRuntime;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.ManagementService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class TaskController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskAdminRuntime taskAdminRuntime;
    @Autowired
    private ManagementService managementService;
    @Autowired
    private TaskRuntime taskRuntime;

    /**
     * 开始一个流程
     *
     * @param processKey 流程标识
     * @return
     */
    @GetMapping(path = "start")
    @ApiOperation(value = "根据流程key启动流程", notes = "每一个流程有对应的一个key这个是某一个流程内固定的写在bpmn内的")
    public RespBase start(@RequestParam(value = "user", required = false, defaultValue = "") String userKey,
                          @RequestParam("processKey") String processKey) {
        HashMap<String, Object> variables = new HashMap<>(1);
        variables.put("userKey", userKey);

        ProcessInstance instance;
        try {
            instance = runtimeService.startProcessInstanceByKey(processKey, variables);
        } catch (Exception e) {
            e.printStackTrace();
            return RespBase.fail(1, "启动失败: " + e.getMessage());
        }

        if (instance != null) {
            Map<String, String> result = new HashMap<>(2);
            // 流程实例ID
            result.put("processID", instance.getId());

            // 流程定义ID
            result.put("processDefinitionKey", instance.getProcessDefinitionId());

            return RespBase.success("启动成功: " + result);
        }
        return RespBase.fail(1, "启动失败: no instance");
    }

    /**
     * 删除多次重试仍然失败，进入死信队列的Job
     *
     * @param taskId
     * @return
     */
    @GetMapping("/delete-task")
    public RespBase completeTask(@RequestParam(value = "taskId") String taskId) {
        runtimeService.deleteProcessInstance(taskId, "delete test");
        log.info(">>> Completed Task: " + taskId);
        return RespBase.success("Delete Task: " + taskId);
    }

}
